import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get_utils/src/platform/platform.dart';
import 'package:pornhub_app/assets/assets.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/m3u8_download/m3u8_download_notify_state.dart';
import 'package:pornhub_app/views/player/controllers/video_play_controller.dart';

import '../../../assets/styles.dart';
import '../../../components/easy_toast.dart';
import '../../../components/popup/dialog/video_downloaded_dialog.dart';
import '../../../components/popup/dialog/video_in_waiting_dialog.dart';
import '../../../model/play/video_detail_model.dart';
import '../../../utils/m3u8_download/m3u8_download_notify.dart';
import '../../../utils/m3u8_download/m3u8_downloader_manager.dart';

class VideoProgressDownloadButton extends StatefulWidget {
  final VideoDetail detail;
  final VideoPlayController vc;
  const VideoProgressDownloadButton(
      {super.key, required this.detail, required this.vc});

  @override
  State<StatefulWidget> createState() => _State();
}

class _State extends State<VideoProgressDownloadButton> {
  late ValueNotifier<M3u8DownloadNotify> _notifier;

  @override
  void initState() {
    _notifier = M3u8DownloadManager.getNotifierAlways(
      widget.detail.videoId ?? 0,
    );
    super.initState();
  }

  void _onTap() {
    if (widget.vc.currentVideo.canWatch == false) {
      widget.vc.showFullPermissionUI();
      return;
    }
    if (GetPlatform.isWeb) {
      SmartDialog.showToast("仅安卓版本支持,请下载安卓客户端!", alignment: Alignment.center);
      return;
    }
    //原生下载
    if (widget.detail.videoUrl!.isEmpty) return;
    final videoId = widget.detail.videoId!;
    final record = M3u8DownloadManager.getRecord(videoId);
    if (record != null) {
      if (record.isSuccess) {
        VideoDownloadedDialog(onConfirm: () => _registerDownload()).show();
        return;
      } else if (record.isWaiting) {
        VideoInWaitingDialog().show();
        return;
      } else {
        // 之前失败直接下载
      }
    }
    _registerDownload();
  }

  void _registerDownload() {
    final notifier = M3u8DownloadManager.registerByDetail(widget.detail);
    if (notifier != null) {
      setState(() {
        _notifier = notifier;
      });
      EasyToast.show('添加任务成功');
    } else {
      EasyToast.show('添加任务失败');
    }
  }

  Widget _buildDownload() {
    final textStyle = TextStyle(
      fontSize: 12.w,
      color: Colors.white,
    );
    return ValueListenableBuilder<M3u8DownloadNotify>(
      valueListenable: _notifier,
      builder: (context, _, __) {
        final value = _notifier.value;
        double progress = .0;
        String? text;
        if (value.state.isNone) {
          text = '下载';
        } else if (value.state.isWaiting) {
          text = '等待中';
        } else if (value.state.isDownloading) {
          progress = value.progress ?? 0;
        } else if (value.state.isSuccess) {
          text = '已下载';
        } else {
          text = '下载失败';
        }
        return Text(
          text ?? '${(progress * 100).toStringAsFixed(2)}%',
          style: textStyle,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Image.asset(
          Assets.iconDownload,
          height: 16.5.w,
        ),
        SizedBox(width: 8.w),
        _buildDownload(),
      ],
    ).onTap(_onTap);
  }
}
